﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.WebSockets;

namespace z.Controllers {
	public class WebSocketController : Controller {
		static List<WebSocket> sockets = new List<WebSocket>();
		[HttpGet]
		public ActionResult Index() {
			if (ControllerContext.HttpContext.IsWebSocketRequest) {
				ControllerContext.HttpContext.AcceptWebSocketRequest(RegistryWS);
			}
			return null;
		}
		public static void SendMessenger(string str) {
			foreach (var x in sockets.ToList()) {
				try{
					ArraySegment<byte> buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(str));
					x.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
				} catch(Exception ex) {
					sockets.Remove(x);
				}
			}
		}
		private async Task RegistryWS(AspNetWebSocketContext context) {
			sockets.Add(context.WebSocket);
			System.Net.WebSockets.WebSocket socket = context.WebSocket;
			while (true) {
				ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
				WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);
				if (socket.State == WebSocketState.Open) {
					string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
					userMessage = "Message from client : " + userMessage;
					buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMessage));
					await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
				} else {
					break;
				}
			}
		}
	}
}
